﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace KMSFanHome2.Controllers
{
    public class AdminController : Controller
    {
        //
        // GET: /Admin/

        public ActionResult Index()
        {
            Models.VotedatabaseContext mv = new Models.VotedatabaseContext();
            List<Models.user> list = mv.users.ToList();
            

            return View();
        }

        public ActionResult Details(int id)
        {
            return View();
        }

        public ActionResult Create()
        {
            return View();
        
        }

        [HttpPost]
        public ActionResult Create(Models.user u)
        {
            try
            {
                string picname = Path.GetFileName(Request.Files["up"].FileName);
                string filepath = Server.MapPath("/Content/") + picname;
                Request.Files["up"].SaveAs(filepath); //保存文件

                u.userpicpath = filepath;
                Models.VotedatabaseContext users = new Models.VotedatabaseContext();
                users.users.Add(u); //改变操作
                users.SaveChanges();

                return RedirectToAction("Index");

            }
            catch (Exception e)
            {
                return View();
            
            }
        }

        public ActionResult Edit(int id)
        {
            return View();
        
        }

        [HttpPost]
        public ActionResult Edit(int id,Models.user u)
        {
            try
            {
                Models.VotedatabaseContext vctx = new Models.VotedatabaseContext();
                vctx.users.Single(m => m.id==id).username = u.username; //查询出指定用户并更新
                vctx.users.Single(m => m.id == id).votecount = u.votecount;
                vctx.SaveChanges();

                return RedirectToAction("Index");
             
            }
            catch (Exception)
            {
                return View();

            }

        }

        /// <summary>
        /// 删除操作
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Delete(int id)
        {
            Models.VotedatabaseContext mv = new Models.VotedatabaseContext();
            //mv.users.Remove();
            mv.users.Remove(mv.users.Single(m=>m.id==id));
            mv.SaveChanges();

            return RedirectToAction("Index");

        }

        /// <summary>
        /// 删除操作
        /// </summary>
        /// <param name="id"></param>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Delete(int id,FormCollection collection)
        {
            try
            {
                return RedirectToAction("Index");

            }
            catch (Exception e)
            {
                return View();
            }
        
        }
    }
}
